using System;
using System.Net.Sockets;
using System.Threading;

namespace monoServer
{
	class AdminConsole
	{
		private DataManager dm;
		private CommunicatorSeriell c;
		private User u;
		
		public static void Main (string[] args)
		{
			AdminConsole ac = new AdminConsole();
			ac.start();

		}
		
		public AdminConsole()
		{
			this.u = new User();
			this.dm = new DataManager();
			this.c = new CommunicatorSeriell(new TcpClient("127.0.0.1",13001), dm, new Logger(new Configuration("/etc/adminconsole")));
		}
		
		public void start()
		{
			Console.WriteLine("Admin-Console of monoserver");
			Console.WriteLine("Type \"help\" or \"help command\" for help");
			Telegram t = null;
			bool loop = true;
			while(loop)
			{
				Console.Write("$ ");
				string line = Console.ReadLine();
				string[] segments = line.Split(' ');
				switch(((String)segments[0]).ToLower())
				{
				case "login":
					this.u = new User();
					this.u.NickName = segments[1];
					this.u.Password = segments[2];
					
					/*
					t = new Telegram("LOGIN", Telegram.REQUEST, this.dm.currentTelegramKey);
					t.addParameter(u.NickName);
					t.addParameter(DataManager.getMD5(u.Password));
					*/
					t = Telegram.getRequest(this.dm.currentTelegramKey, "LOGIN", this.u.NickName, this.u.Password);
					this.c.sendTelegram(t);
					
					t = this.c.readTelegram(Telegram.RESPONSE, t.key);
					if(t[1].Equals("OK"))
					{
						// Login erfolgreich
						Console.WriteLine("Login erfolgreich");
						this.u.IsLoggedIn = true;
					} else {
						Console.WriteLine("Login fehlgeschlagen: " + t[2]);
					}
					
					
					break;
					
				case "stopserver":
					// TODO Adminlevel muss noch überprüft werden
					if(u.IsLoggedIn)
					{
						//t = new Telegram("STOPSERVER", Telegram.REQUEST, this.dm.currentTelegramKey);
						t = Telegram.getRequest(this.dm.currentTelegramKey, "STOPSERVER");
						if(segments[1].Equals("soft"))
							t.addParameter("soft");
						if(segments[1].Equals("hard"))
							t.addParameter("hard");
						this.c.sendTelegram(t);
					} else {
						// Du musst dich zuerst einloggen
						Console.WriteLine("Bitte zuerst einloggen");
					}
					break;
					
				case "getsessions":
					//t = new Telegram("GETSESSIONS", Telegram.REQUEST, this.dm.currentTelegramKey);
					t = Telegram.getRequest(this.dm.currentTelegramKey, "GETSESSIONS");
					this.c.sendTelegram(t);
					break;
				case "exit":
					loop = false;
					break;

				default:
					Console.WriteLine("Unknown Command: " + segments[0]);
					break;
				}
			}
		}
	}
}
